package com.ruoyi.web.controller.thirdAPI;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.tax.BaseResponse;
import com.ruoyi.system.domain.tax.FluxPressureData;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 * @description 第三方接口（拓安信水表） 采集频率5分钟，6小时上报 历史数据最多存储3天
 * @data 2025/9/25 13:55
 */
@RestController
@RequestMapping("/taxApi")
public class TAXDataController {

    @Autowired
    private IWaterMeterDatahistoryService waterMeterDatahistoryService;
    @Autowired
    private IWaterMeterService waterMeterService;
    @Autowired
    private IWaterUserService waterUserService;
    @Autowired
    private IWaterYcmeterDatahistoryService historyService;
    @Autowired
    private IWaterDailyUsageService waterDailyUsageService;
    @Autowired
    private IWaterWeeklyUsageService waterWeeklyUsageService;
    /**
     * 获取第三方水表数据
     * 参数 /taxApi/pressure?time=2025-10-10 11:56
     * @return
     */
    @PostMapping("/pressure")
    public BaseResponse<FluxPressureData> getFluxPressureData(String time) {
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.MINUTE, -5);
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        String startTime = sdf.format(calendar.getTime());
        for(WaterMeter meter : waterMeters){
            if(meter.getMeterNo().equals("2412208000")){
                waterMeterDatahistoryService.syncWaterMeterData(meter,time);
            }
        }
        return null;
    }

    /**
     * 水表数据统计(日用水量)
     */
    @PostMapping("/analysisDay")
    public void analysisDay(){
        String dateStr = "2025-10-08";
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期并计算后一天
        LocalDate date = LocalDate.parse(dateStr, formatter);
        for(int i=0;i<=6;i++){
            LocalDate nextDay = date.plusDays(i+1);
            String readDate = nextDay.format(formatter);
            System.err.println(readDate);
            insertWaterDailyUsage(readDate);
        }
    }
    /**
     * 水表数据统计(周用水量)
     */
    @PostMapping("/analysisWeek")
    public void analysisWeek(){
        String startDateStr = "2025-10-06";
        String endDateStr = "2025-10-12";
        Date d1 = DateUtils.parseDate(startDateStr);
        Date d2 = DateUtils.parseDate(endDateStr);
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
        WaterDailyUsage waterDailyUsage = new WaterDailyUsage();
        waterDailyUsage.setStartDay(startDateStr);
        waterDailyUsage.setEndDay(endDateStr);
        List<WaterDailyUsage> dailyUsageList = waterDailyUsageService.selectWaterDailyUsageList(waterDailyUsage);
        dailyUsageList.sort(Comparator.comparing(WaterDailyUsage::getReadingDate,
                Comparator.nullsLast(String::compareTo)));
        BigDecimal a = dailyUsageList.get(0).getPreviousReading();
        BigDecimal b = dailyUsageList.get(dailyUsageList.size()-1).getCurrentReading();
        for(WaterMeter meter : waterMeters){
            if(meter.getMeterNo().equals("2412208000")){
                WaterWeeklyUsage waterWeeklyUsage = new WaterWeeklyUsage();
                waterWeeklyUsage.setUserId(meter.getUserId());
                waterWeeklyUsage.setMeterNo(meter.getMeterNo());
                waterWeeklyUsage.setUserName(meter.getUserName());
                waterWeeklyUsage.setStartDate(d1);
                waterWeeklyUsage.setEndDate(d2);
                waterWeeklyUsage.setWeeklyConsumption(b.subtract(a));
                waterWeeklyUsageService.insertWaterWeeklyUsage(waterWeeklyUsage);
            }
        }
    }

    public void insertWaterDailyUsage(String readDate){
        System.out.println("开始执行水表数据统计任务");
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0"); // 0:远传表
        List<WaterMeter> waterMeters =waterMeterService.selectWaterMeterList(waterMeter);
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 解析日期并计算前一天
        LocalDate date = LocalDate.parse(readDate, formatter);
//        LocalDate previousDay = date.minusDays(1);
        LocalDate nextDay = date.plusDays(1);
        dataHistory.setMeterNo("24120137894");
        dataHistory.setStartTime(readDate+" 00:00");
        dataHistory.setEndTime(nextDay.format(formatter)+" 01:00");
        List<WaterYcmeterDatahistory> dataHistoryList = historyService.selectWaterYcmeterDatahistoryList(dataHistory);
        dataHistoryList.sort(Comparator.comparing(WaterYcmeterDatahistory::getReadDate,
                Comparator.nullsLast(String::compareTo)));
        BigDecimal a = new BigDecimal(dataHistoryList.get(0).getCurrentReading());
        BigDecimal b = new BigDecimal(dataHistoryList.get(dataHistoryList.size()-1).getCurrentReading());
        for(WaterMeter meter : waterMeters){
            if(meter.getMeterNo().equals("24120137894")){
                WaterDailyUsage dailyUsage = new WaterDailyUsage();
                dailyUsage.setUserId(meter.getUserId());
                dailyUsage.setMeterNo(meter.getMeterNo());
                dailyUsage.setUserName(meter.getUserName());
                dailyUsage.setPreviousReading(a);
                dailyUsage.setCurrentReading(b);
                dailyUsage.setDailyConsumption(b.subtract(a));
                dailyUsage.setReadingDate(readDate);
                waterDailyUsageService.insertWaterDailyUsage(dailyUsage);
            }
        }
    }

    /**
     * 获取实时数据
     * @return
     */
    @PostMapping("/getRealData")
    @ResponseBody
    public List<WaterMeter> getRealData(){
        List<WaterMeter> list = new ArrayList<>();
        WaterMeter waterMeter = new WaterMeter();
        waterMeter.setMeterType("0");
        List<WaterMeter> meters = waterMeterService.selectWaterMeterList(waterMeter);
        for(WaterMeter meter : meters){
            if(StringUtils.isNotEmpty(meter.getReadDate())){
                list.add(meter);
            }
        }
        return list;
    }

    /**
     * 获取历史数据
     * @return
     */
    @PostMapping("/getHistoryData")
    @ResponseBody
    public List<WaterYcmeterDatahistory> getHistoryData(String meterNo){
        WaterYcmeterDatahistory dataHistory = new WaterYcmeterDatahistory();
        dataHistory.setMeterNo(meterNo);
        return historyService.selectWaterYcmeterDatahistoryList(dataHistory);
    }

    @PostMapping("/getUserList")
    @ResponseBody
    public List<WaterUser> getUserList(String userId){
        WaterUser waterUser = new WaterUser();
        waterUser.setUserId(userId);
        List<WaterUser> list = waterUserService.selectWaterUserList(waterUser);
        return list;
    }

}
